package com.auto.learning.tools;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加密、解密 采用CBC模式，使用PKCS5进行补码 加密后的数据将使用Base64进行编码
 * 
 * 注意：若变更了密钥或偏移向量串，则会导致原加密数据无法解密。
 * 
 * @author Chen Mohan
 */
public class AES {

	private static final String AES_KEY = "L2HGM84N24V5UYRB"; // 密钥
	private static final String AES_IV = "5PLOEQ87Z5LM9K2U"; // 偏移向量串
	private static final String AES_MODE = "AES/CBC/PKCS5Padding"; // 模式

	/**
	 * AES加密
	 */
	public static String encrypt(String s) {
		SecretKeySpec skeySpec = new SecretKeySpec(AES.AES_KEY.getBytes(),
				"AES");
		IvParameterSpec iv = new IvParameterSpec(AES.AES_IV.getBytes());
		try {
			Cipher cipher = Cipher.getInstance(AES_MODE);
			cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
			byte[] result = cipher.doFinal(s.getBytes("UTF-8"));
			return Base64.encode(result);
		} catch (Throwable t) {
			throw new RuntimeException("AES encrypt failed", t);
		}
	}

	/**
	 * AES解密
	 */
	public static String decrypt(String s) {
		IvParameterSpec iv = new IvParameterSpec(AES.AES_IV.getBytes());
		try {
			byte[] resource = Base64.decode(s);
			SecretKeySpec skeySpec = new SecretKeySpec(
					AES.AES_KEY.getBytes("ASCII"), "AES");
			Cipher cipher = Cipher.getInstance(AES_MODE);
			cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
			return new String(cipher.doFinal(resource));
		} catch (Throwable t) {
			return null;
		}
	}
}
